package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"login/dao"
	"login/models"
	"net/http"
)

func Login(c *gin.Context) {
	if c.Request.Method == "GET" {
		c.HTML(http.StatusOK, "login.html", nil)
	}
	if c.Request.Method == "POST" {
		// 接收表单参数
		username := c.PostForm("username")
		password := c.PostForm("password")
		// 从数据库获取数据
		/*
			使用Map查询
			db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users)
		*/
		var result models.User
		dao.DB.Debug().Where(map[string]interface{}{"username": username, "password": password}).
			Find(&result)
		// 校验参数
		if username == result.Username && password == result.Password {
			fmt.Println("登陆成功")
			// 跳转到首页
			c.HTML(http.StatusOK, "index.html", gin.H{
				"username": username,
			})
		} else {
			// 跳转到登陆页 并且渲染错误数据
			c.HTML(http.StatusOK, "login.html", gin.H{
				"code":    1,
				"message": "用户名或者密码错误",
			})
		}
	}
}

func Index(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", nil)
}

func Register(c *gin.Context) {
	if c.Request.Method == "GET" {
		c.HTML(http.StatusOK, "register.html", nil)
	}
	if c.Request.Method == "POST" {
		// 获取参数
		type register struct {
			Username  string `form:"username"`
			Password  string `form:"password"`
			Password2 string `form:"password2"`
		}
		var reg register
		err := c.ShouldBind(&reg)
		if err != nil {
			fmt.Println("获取参数失败")
		}
		// 校验参数
		if reg.Password == reg.Password2 {
			c.Redirect(http.StatusMovedPermanently, "/login") // 重定向到登录页

			// 保存账号密码
			dao.DB.Debug().Create(&models.User{
				Username: reg.Username,
				Password: reg.Password,
			})
		} else {
			c.HTML(http.StatusOK, "register.html", gin.H{
				"code":    1,
				"message": "两次输入的密码不正确",
			})
		}
	}
}
